#!/usr/bin/env python
#_*_ coding:utf-8 _*_

import sys, os
from pyscript.core import Register
from pyscript.core.config import Config
from multiprocessing import Process
from task.collect.dangle import Dangle
from task.collect.qihu import Qihu

reload(sys)
fileSystemEncode = sys.getfilesystemencoding()
sys.setdefaultencoding('utf-8')
ROOT_PATH = os.path.realpath(os.path.dirname(sys.argv[0]))
CONFIG_PATH = os.path.join(ROOT_PATH, 'conf')
BIN_PATH = os.path.join(ROOT_PATH, 'bin')
VIEW_PATH = os.path.join(ROOT_PATH, 'view')

def main():
    Register.set('bin', BIN_PATH)
    Register.set('conf', CONFIG_PATH)
    Register.set('root', ROOT_PATH)
    Register.set('view', VIEW_PATH)
    Register.set('filesystemencode', fileSystemEncode)
    tasks = Register.get('tasks', {})
    defaultConfig = os.path.join(CONFIG_PATH, 'default.yml.default')
    config = Config()

    if os.path.exists(defaultConfig):
        config.load_config(defaultConfig)

    defaultConfig = os.path.join(CONFIG_PATH, 'default.yml')

    if os.path.exists(defaultConfig):
        config.load_config(defaultConfig)

    if len(tasks):
        task_pool = []

        for name, task in tasks.iteritems():
            task_pool.append(task().run)

        process_pool = []

        for process in task_pool:
            _p = Process(target = process)
            _p.start()
            process_pool.append(_p)

        map(lambda p: p.join(), process_pool)

    else:
        print "No task"

if '__main__' == __name__:
    main()
